<template>
  <div class="home-container">
    <div class="header-section">
      <div class="category-nav">
        <div v-for="category in categories" :key="category.id" class="category-item"
          :class="{ active: currentCategory.id === category.id }" @click="selectCategory(category)">
          {{ category.name }}
        </div>
      </div>
      <div class="header-actions">
        <el-button @click="goToSearch">
          <el-icon>
            <Search />
          </el-icon>
          问大师学中医
        </el-button>
        <el-button class="review-btn" type="primary" @click="goToReview">
          <el-icon>
            <Calendar />
          </el-icon>
          复习计划
        </el-button>
        <el-button class="rank-btn" type="primary" @click="goToRank">
          <el-icon>
            <Trophy />
          </el-icon>
          积分排行榜
        </el-button>
      </div>
    </div>

    <div class="content-section">
      <div class="knowledge-list">
        <el-card v-for="item in knowledgeList" :key="item.id" class="knowledge-card" @click="showKnowledgeDetail(item)">
          <h3 class="title">{{ item.title }}</h3>
          <div class="subtitle">{{ item.subtitle }}</div>
          <div class="content">{{ item.content }}</div>
          <div class="card-footer">
            <el-button text type="primary">
              <el-icon>
                <View />
              </el-icon>
              查看详情
            </el-button>
          </div>
        </el-card>
      </div>

      <!-- 知识详情对话框 -->
      <el-dialog v-model="knowledgeDetailVisible" :title="currentKnowledge.title" width="50%"
        class="knowledge-detail-dialog">
        <div class="knowledge-detail">
          <div class="detail-subtitle">{{ currentKnowledge.subtitle }}</div>
          <div class="detail-content">{{ currentKnowledge.content }}</div>
        </div>
      </el-dialog>

      <div class="quiz-section">
        <el-button type="primary" class="quiz-btn" @click="startQuiz">
          <el-icon>
            <QuestionFilled />
          </el-icon>
          开始答题
        </el-button>
      </div>
    </div>

    <!-- 答题对话框 -->
    <el-dialog v-model="quizDialogVisible" :title="'知识问答 - ' + currentCategory.name" width="60%"
      :close-on-click-modal="false">
      <div v-if="currentQuestion" class="quiz-content">
        <div class="question-info">
          <span class="difficulty">
            难度：
            <el-rate v-model="currentQuestion.difficulty" :max="5" disabled show-score text-color="#ff9900" />
          </span>
        </div>

        <div class="question-content">{{ currentQuestion.content }}</div>

        <div class="options">
          <el-radio-group v-model="userAnswer">
            <el-radio v-for="(option, index) in currentQuestion.options" :key="index" :value="option.charAt(0)"
              class="option-item">
              {{ option }}
            </el-radio>
          </el-radio-group>
        </div>
      </div>

      <div class="quiz-progress">
        {{ currentQuestionIndex + 1 }} / {{ questionList.length }}
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="quizDialogVisible = false">退出答题</el-button>
          <el-button type="primary" @click="nextQuestion" :disabled="!userAnswer">
            {{ isLastQuestion ? '提交' : '下一题' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 答题结果对话框 -->
    <el-dialog v-model="resultDialogVisible" title="答题结果分析" width="50%" center>
      <div class="quiz-result">
        <div class="result-header">
          <div class="score-circle">
            <div class="score-number">{{ quizResult.totalScore }}</div>
            <div class="score-label">总分</div>
          </div>
          <div class="result-summary">
            <div class="summary-item">
              <el-icon>
                <Check />
              </el-icon>
              <span>答对题数：{{ quizResult.correctCount }}</span>
            </div>
            <div class="summary-item">
              <el-icon>
                <Timer />
              </el-icon>
              <span>用时：{{ quizResult.timeUsed || '2分30秒' }}</span>
            </div>
            <div class="summary-item">
              <el-icon>
                <Star />
              </el-icon>
              <span>正确率：{{ Math.round((quizResult.correctCount / questionList.length) * 100) }}%</span>
            </div>
          </div>
        </div>

        <el-divider>答题分析</el-divider>

        <div class="analysis-section">
          <div class="analysis-item">
            <h4>知识点掌握情况</h4>
            <div class="knowledge-progress">
              <div class="progress-item">
                <span>中药基础</span>
                <el-progress :percentage="85" :color="'#67C23A'" />
              </div>
              <div class="progress-item">
                <span>经典理论</span>
                <el-progress :percentage="70" :color="'#E6A23C'" />
              </div>
              <div class="progress-item">
                <span>临床应用</span>
                <el-progress :percentage="60" :color="'#F56C6C'" />
              </div>
            </div>
          </div>

          <div class="analysis-item">
            <h4>答题建议</h4>
            <div class="suggestion-list">
              <div class="suggestion-item">
                <el-icon>
                  <InfoFilled />
                </el-icon>
                <span>建议加强经典理论的学习，特别是《黄帝内经》和《伤寒论》的基础知识</span>
              </div>
              <div class="suggestion-item">
                <el-icon>
                  <InfoFilled />
                </el-icon>
                <span>在临床应用方面需要更多实践，建议多关注实际案例</span>
              </div>
              <div class="suggestion-item">
                <el-icon>
                  <InfoFilled />
                </el-icon>
                <span>中药基础掌握较好，可以进一步深入学习中药配伍理论</span>
              </div>
            </div>
          </div>
        </div>

        <div class="result-footer">
          <el-button type="primary" @click="closeResult">完成</el-button>
          <el-button @click="restartQuiz">重新答题</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { QuestionFilled, Trophy, View, Check, Timer, Star, InfoFilled, Calendar, Search } from '@element-plus/icons-vue'
import axios from 'axios'
import { useUserStore } from '@/store/modules/user'

const router = useRouter()
const userStore = useUserStore()

// 创建 axios 实例
const request = axios.create({
  baseURL: '/api',
  timeout: 5000
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    const token = userStore.getToken
    if (token) {
      // 直接使用 token，不添加 Bearer 前缀
      config.headers['Authorization'] = token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      userStore.logout()
    } else {
      ElMessage.error(error.message || '请求失败')
    }
    return Promise.reject(error)
  }
)

// 科普分类
const categories = [
  { id: 1, name: '中药基础' },
  { id: 2, name: '针灸推拿' },
  { id: 3, name: '养生保健' },
  { id: 4, name: '经典理论' },
  { id: 5, name: '四季养生' },
  { id: 6, name: '食疗方案' }
]

const currentCategory = ref(categories[0])
const knowledgeList = ref([])
const questionList = ref([])
const currentQuestionIndex = ref(0)
const userAnswer = ref('')
const userAnswers = ref([])
const quizDialogVisible = ref(false)
const resultDialogVisible = ref(false)
const quizResult = ref({ totalScore: 0, correctCount: 0 })

// 知识详情相关
const knowledgeDetailVisible = ref(false)
const currentKnowledge = ref({
  title: '',
  subtitle: '',
  content: ''
})

const currentQuestion = computed(() => {
  return questionList.value[currentQuestionIndex.value] || null
})

const isLastQuestion = computed(() => {
  return currentQuestionIndex.value === questionList.value.length - 1
})

// 选择分类
const selectCategory = async (category) => {
  currentCategory.value = category
  await fetchKnowledgeList()
}

// 获取知识列表
const fetchKnowledgeList = async () => {
  try {
    const response = await request.get(`/v1/medical/knowledge/show/${currentCategory.value.id}`)
    if (response.data.code === '0000') {
      knowledgeList.value = response.data.data
    }
  } catch (error) {
    console.error('获取知识列表失败:', error)
  }
}

// 开始答题
const startQuiz = async () => {
  try {
    const response = await request.get(`/v1/medical/question/show/${currentCategory.value.id}`)
    if (response.data.code === '0000') {
      questionList.value = response.data.data
      currentQuestionIndex.value = 0
      userAnswers.value = []
      userAnswer.value = ''
      quizDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取题目失败:', error)
  }
}

// 下一题或提交
const nextQuestion = async () => {
  // 记录答案
  userAnswers.value.push({
    id: currentQuestion.value.id,
    userAnswer: userAnswer.value,
    difficulty: currentQuestion.value.difficulty
  })

  if (isLastQuestion.value) {
    // 提交答案
    try {
      const response = await request.post('/v1/medical/question/answer_submit', {
        categoryId: currentCategory.value.id,
        answers: userAnswers.value
      })

      if (response.data.code === '0000') {
        quizResult.value = response.data.data
        quizDialogVisible.value = false
        resultDialogVisible.value = true
      }
    } catch (error) {
      console.error('提交答案失败:', error)
    }
  } else {
    // 下一题
    currentQuestionIndex.value++
    userAnswer.value = ''
  }
}

// 关闭结果
const closeResult = () => {
  resultDialogVisible.value = false
  userAnswers.value = []
}

// 重新开始答题
const restartQuiz = () => {
  resultDialogVisible.value = false
  startQuiz()
}

// 移除排行榜相关的数据和方法
const goToRank = () => {
  router.push('/rank')
}

// 显示知识详情
const showKnowledgeDetail = (item) => {
  currentKnowledge.value = item
  knowledgeDetailVisible.value = true
}

// 跳转到复习计划页面
const goToReview = () => {
  router.push('/review')
}

const goToSearch = () => {
  router.push('/search')
}

onMounted(() => {
  console.log('Current token:', userStore.getToken)
  fetchKnowledgeList()
})
</script>

<style lang="scss" scoped>
.home-container {
  height: calc(100vh - 100px);
  padding: 0;

  .header-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .category-nav {
      flex: 1;
      display: grid;
      grid-template-columns: repeat(6, 1fr);
      gap: 10px;
      margin-right: 20px;
      padding: 15px;
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

      .category-item {
        text-align: center;
        padding: 10px;
        cursor: pointer;
        border-radius: 4px;
        transition: all 0.3s;

        &:hover {
          background: #f5f7fa;
        }

        &.active {
          background: var(--el-color-primary);
          color: #fff;
        }
      }
    }

    .header-actions {
      display: flex;
      gap: 10px;

      .review-btn,
      .rank-btn {
        .el-icon {
          margin-right: 5px;
        }
      }
    }
  }

  .content-section {
    flex: 1;
    overflow-y: auto;

    .knowledge-list {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
      gap: 20px;
      padding: 0 15px;
      margin-bottom: 30px;

      .knowledge-card {
        height: 100%;
        display: flex;
        flex-direction: column;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          transform: translateY(-5px);
          box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
        }

        .title {
          font-size: 18px;
          margin: 0 0 10px;
          color: #2c3e50;
        }

        .subtitle {
          font-size: 14px;
          color: #606266;
          margin-bottom: 15px;
        }

        .content {
          flex: 1;
          font-size: 14px;
          color: #666;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 3;
          -webkit-box-orient: vertical;
          margin-bottom: 10px;
        }

        .card-footer {
          text-align: right;
          padding-top: 10px;
          border-top: 1px solid #f0f0f0;

          .el-button {
            padding: 4px 0;

            .el-icon {
              margin-right: 4px;
            }
          }
        }
      }
    }

    .quiz-section {
      text-align: center;
      margin: 30px 0;

      .quiz-btn {
        font-size: 16px;
        padding: 12px 24px;

        .el-icon {
          margin-right: 8px;
        }
      }
    }
  }
}

.quiz-content {
  .question-info {
    margin-bottom: 20px;
  }

  .question-content {
    font-size: 16px;
    margin-bottom: 20px;
    color: #2c3e50;
  }

  .options {
    .el-radio-group {
      display: flex;
      flex-direction: column;
      gap: 15px;
    }

    .option-item {
      margin: 0;
    }
  }
}

.quiz-progress {
  text-align: center;
  margin-top: 20px;
  color: #909399;
}

.quiz-result {
  padding: 20px;

  .result-header {
    display: flex;
    align-items: center;
    gap: 40px;
    margin-bottom: 20px;

    .score-circle {
      width: 120px;
      height: 120px;
      border-radius: 50%;
      background: linear-gradient(135deg, #409EFF 0%, #67C23A 100%);
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: white;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

      .score-number {
        font-size: 36px;
        font-weight: bold;
      }

      .score-label {
        font-size: 14px;
        margin-top: 5px;
      }
    }

    .result-summary {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 15px;

      .summary-item {
        display: flex;
        align-items: center;
        gap: 10px;
        font-size: 16px;
        color: #606266;

        .el-icon {
          font-size: 20px;
          color: #409EFF;
        }
      }
    }
  }

  .analysis-section {
    .analysis-item {
      margin-bottom: 30px;

      h4 {
        font-size: 16px;
        color: #303133;
        margin-bottom: 15px;
        font-weight: 600;
      }

      .knowledge-progress {
        .progress-item {
          margin-bottom: 15px;

          span {
            display: block;
            margin-bottom: 8px;
            color: #606266;
          }
        }
      }

      .suggestion-list {
        .suggestion-item {
          display: flex;
          align-items: flex-start;
          gap: 10px;
          margin-bottom: 12px;
          color: #606266;
          line-height: 1.5;

          .el-icon {
            color: #E6A23C;
            margin-top: 3px;
          }
        }
      }
    }
  }

  .result-footer {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 30px;
  }
}

// 响应式设计
@media screen and (max-width: 768px) {
  .home-container {
    .header-section {
      flex-direction: column;
      gap: 15px;

      .category-nav {
        width: 100%;
        margin-right: 0;
        grid-template-columns: repeat(3, 1fr);
      }

      .header-actions {
        width: 100%;
      }
    }
  }
}

// 知识详情对话框样式
.knowledge-detail-dialog {
  .knowledge-detail {
    padding: 20px;
    background: #f8f9fa;
    border-radius: 8px;

    .detail-subtitle {
      font-size: 16px;
      color: #606266;
      margin-bottom: 20px;
      padding-bottom: 15px;
      border-bottom: 1px solid #ebeef5;
    }

    .detail-content {
      font-size: 14px;
      color: #2c3e50;
      line-height: 1.8;
      white-space: pre-line;
    }
  }
}
</style>